import { defineStore } from 'pinia'
import { http, setAuthHeader, clearAuth } from '../api/http'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    username: '',
    password: '',
    authenticated: false,
    roles: [] as string[],
    menus: [] as { name: string; path: string }[],
    loading: false,
    error: ''
  }),
  actions: {
    async login(username: string, password: string) {
      this.loading = true; this.error = ''
      try {
        setAuthHeader(username, password)
        const res = await http.get('/auth/me')
        this.username = username
        this.password = password
        this.authenticated = !!res.data.authenticated
        this.roles = res.data.roles || []
        this.menus = res.data.menus || []
      } catch (e: any) {
        this.error = e?.response?.data?.message || e?.message || '登录失败'
        this.authenticated = false
      } finally {
        this.loading = false
      }
    }
    , logout() {
      clearAuth()
      this.username = ''
      this.password = ''
      this.authenticated = false
      this.roles = []
      this.menus = []
    }
  }
})